const express = require('express');
const router = express.Router();
const { pool } = require('../config/db');

// 获取学生消息列表
router.get('/student/messages', async (req, res) => {
  try {
    console.log('获取学生消息请求参数:', req.query);
    
    // 从请求中获取用户ID
    const userId = req.query.userId;
    
    if (!userId) {
      console.log('缺少用户ID参数');
      return res.json({ messages: [], unreadCount: 0 });
    }
    
    // 查询用户ID对应的数据库ID
    const userQuery = `SELECT id FROM users WHERE userId = ?`;
    const [userResult] = await pool.query(userQuery, [userId]);
    
    if (userResult.length === 0) {
      console.log('找不到用户');
      return res.json({ messages: [], unreadCount: 0 });
    }
    
    const dbUserId = userResult[0].id;
    
    // 查询消息
    const query = `
      SELECT id, senderId, senderName, title, content, type, isRead, sendTime
      FROM messages
      WHERE receiverId = ?
      ORDER BY sendTime DESC
    `;
    
    const [messages] = await pool.query(query, [dbUserId]);
    
    // 计算未读消息数量
    const unreadCount = messages.filter(msg => !msg.isRead).length;
    
    console.log('返回消息数据:', { messages, unreadCount });
    res.json({ messages, unreadCount });
  } catch (error) {
    console.error('获取学生消息失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 标记消息为已读
router.put('/student/messages/:id/read', async (req, res) => {
  try {
    const messageId = req.params.id;
    console.log(`标记消息 ${messageId} 为已读`);
    
    const query = `
      UPDATE messages
      SET isRead = 1, readTime = NOW()
      WHERE id = ?
    `;
    
    await pool.query(query, [messageId]);
    
    res.json({ success: true });
  } catch (error) {
    console.error('标记消息已读失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 标记所有消息为已读
router.put('/student/messages/read-all', async (req, res) => {
  try {
    const userId = req.query.userId;
    
    if (!userId) {
      return res.status(400).json({ message: '缺少用户ID参数' });
    }
    
    // 查询用户ID对应的数据库ID
    const userQuery = `SELECT id FROM users WHERE userId = ?`;
    const [userResult] = await pool.query(userQuery, [userId]);
    
    if (userResult.length === 0) {
      return res.status(404).json({ message: '找不到用户' });
    }
    
    const dbUserId = userResult[0].id;
    
    console.log('标记所有消息为已读');
    
    const query = `
      UPDATE messages
      SET isRead = 1, readTime = NOW()
      WHERE receiverId = ? AND isRead = 0
    `;
    
    await pool.query(query, [dbUserId]);
    
    res.json({ success: true });
  } catch (error) {
    console.error('标记所有消息已读失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});


// 获取消息列表
router.get('/', async (req, res) => {
  try {
    console.log('消息列表路由被访问，参数:', req.query);
    const { userId, limit = 10 } = req.query;
    
    if (!userId) {
      return res.status(400).json({ message: '缺少必要参数' });
    }
    
    // 查询用户ID对应的数据库ID
    const userQuery = `SELECT id FROM users WHERE userId = ?`;
    const [userResult] = await pool.query(userQuery, [userId]);
    
    if (userResult.length === 0) {
      console.log('找不到用户');
      return res.json([]);
    }
    
    const dbUserId = userResult[0].id;
    
    // 查询消息列表
    const query = `
      SELECT m.id, m.title, m.content, m.sendTime, m.isRead, u.name as senderName
      FROM messages m
      JOIN users u ON m.senderId = u.id
      WHERE m.receiverId = ?
      ORDER BY m.sendTime DESC
      LIMIT ?
    `;
    
    console.log('执行SQL查询:', query, [dbUserId, parseInt(limit)]);
    
    const [rows] = await pool.query(query, [dbUserId, parseInt(limit)]);
    console.log('消息列表查询结果:', rows);
    
    // 格式化日期
    const formattedRows = rows.map(message => ({
      ...message,
      sendTime: new Date(message.sendTime).toLocaleString('zh-CN')
    }));
    
    res.json(formattedRows);
  } catch (error) {
    console.error('获取消息列表失败:', error);
    res.json([]);
  }
});

// 获取消息详情
router.get('/:id', async (req, res) => {
  try {
    const messageId = req.params.id;
    console.log('消息详情路由被访问，消息ID:', messageId);
    
    // 查询消息详情
    const query = `
      SELECT m.id, m.title, m.content, m.sendTime, m.isRead, 
             u.name as senderName, u.avatar as senderAvatar
      FROM messages m
      JOIN users u ON m.senderId = u.id
      WHERE m.id = ?
    `;
    
    const [rows] = await pool.query(query, [messageId]);
    
    if (rows.length === 0) {
      return res.status(404).json({ message: '消息不存在' });
    }
    
    const message = rows[0];
    
    // 格式化日期
    message.sendTime = new Date(message.sendTime).toLocaleString('zh-CN');
    
    // 标记消息为已读
    await pool.query('UPDATE messages SET isRead = 1 WHERE id = ?', [messageId]);
    
    res.json(message);
  } catch (error) {
    console.error('获取消息详情失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 发送消息
router.post('/', async (req, res) => {
  try {
    console.log('发送消息路由被访问，请求体:', req.body);
    const { senderId, receiverId, title, content } = req.body;
    
    if (!senderId || !receiverId || !title || !content) {
      return res.status(400).json({ message: '缺少必要参数' });
    }
    
    // 查询发送者ID
    const senderQuery = `SELECT id FROM users WHERE userId = ?`;
    const [senderResult] = await pool.query(senderQuery, [senderId]);
    
    if (senderResult.length === 0) {
      return res.status(404).json({ message: '发送者不存在' });
    }
    
    const dbSenderId = senderResult[0].id;
    
    // 查询接收者ID
    const receiverQuery = `SELECT id FROM users WHERE userId = ?`;
    const [receiverResult] = await pool.query(receiverQuery, [receiverId]);
    
    if (receiverResult.length === 0) {
      return res.status(404).json({ message: '接收者不存在' });
    }
    
    const dbReceiverId = receiverResult[0].id;
    
    // 获取发送者姓名
    const senderNameQuery = `SELECT name FROM users WHERE id = ?`;
    const [senderNameResult] = await pool.query(senderNameQuery, [dbSenderId]);
    const senderName = senderNameResult[0].name;
    
    // 插入消息
    const query = `
      INSERT INTO messages (senderId, senderName, receiverId, title, content, sendTime, isRead, type)
      VALUES (?, ?, ?, ?, ?, NOW(), 0, 'normal')
    `;
    
    const [result] = await pool.query(query, [dbSenderId, senderName, dbReceiverId, title, content]);
    
    res.status(201).json({
      message: '发送成功',
      messageId: result.insertId
    });
  } catch (error) {
    console.error('发送消息失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

module.exports = router;